<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <a-form
          layout="inline"
          :model="searchEbook"
      >
        <a-form-item>
          <a-input v-model:value="searchEbook.name" placeholder="搜索名称">
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-space size="small">
            <a-button type="primary" @click="handleQueryByName({page:1, size: pagination.pageSize})">
              查询
            </a-button>
            <a-button type="primary" @click="add">
              新增
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
      <a-table :columns="columns"
               :row-key="record => record.id"
               :data-source="ebooks"
               :pagination="pagination"
               :loading="loading"
               @change="handleTableChange">
        <template #cover="{ text:cover }">
          <img v-if="cover" :src="cover" alt="avatar" style="height: 50px;width: 50px"/>
        </template>
        <template v-slot:category="{text, record}">
          <span>{{ getCategoryName(record.category1Id) }} / {{ getCategoryName(record.category2Id) }}</span>
        </template>
        <template v-slot:action="{ text, record}">
          <a-space size="small">
            <router-link :to="'/admin/doc?ebookId=' + record.id">
              <a-button type="primary">
                文档编辑
              </a-button>
            </router-link>
            <a-button type="primary" @click="edit(record)">
              编辑
            </a-button>
            <a-popconfirm
                title="该删除操作不可逆-确定删除吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record.id)"
            >
              <a-button type="primary" danger>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
  <a-modal title="电子书表单"
           v-model:visible="modalVisible"
           :confirm-loading="modalLoading"
           @ok="handleModalOk">
    <a-form :model="ebook" :label-col="{ span : 6}" :wrapper-col="wrapperCol">
      <a-form-item label="封面">
        <a-input v-model:value="ebook.cover"/>
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="ebook.name"/>
      </a-form-item>
      <a-form-item label="分类">
        <a-cascader v-model:value="categoryIds"
                    :field-names="{ label:'name',value:'id',children:'children' }"
                    :options="level1"
        />
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-model:value="ebook.description"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import {defineComponent, onMounted, ref} from 'vue';
import axios from "axios";
import {message} from 'ant-design-vue'
import {Tool} from "@/util/tool";

export default defineComponent({
  name: 'AdminEbook',
  setup() {
    // 图书信息响应式对象
    const ebooks = ref();
    // 页码信息
    const pagination = ref({
      current: 1,
      pageSize: 5,
      total: 0
    });
    // 表示加载状态
    const loading = ref(false);
    // 表格列信息
    const columns = [
      {
        title: '封面',
        dataIndex: 'cover',
        slots: {customRender: 'cover'},
      },
      {
        title: '名称',
        dataIndex: 'name',
      },
      {
        title: '分类',
        slots: {customRender: 'category'}
      },
      {
        title: '文档数',
        dataIndex: 'docCount',
      },
      {
        title: '阅读数',
        dataIndex: 'viewCount',
      },
      {
        title: '点赞数',
        dataIndex: 'voteCount',
      },
      {
        title: 'Action',
        key: 'action',
        slots: {customRender: 'action'},
      },
    ];
    // 图书查询对象
    const searchEbook = ref();
    searchEbook.value = {}
    /**
     * 数据查询
     */
    const handleQuery = (params: any) => {
      loading.value = true;
      ebooks.value = [];
      axios.get("/ebook/list", {
        params: {
          page: params.page,
          size: params.size,
          name: searchEbook.value.name
        }
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          ebooks.value = data.content.list;
          // 重置分页按钮
          pagination.value.current = params.page;
          pagination.value.total = data.content.total;
        } else {
          message.error(data.message);
        }

      })
    };

    /**
     * 根据name查询电子书信息
     */
    const handleQueryByName = (params: any) => {
      loading.value = true;
      ebooks.value = [];
      axios.get("/ebook/search", {
        params: {
          page: params.page,
          size: params.size,
          name: searchEbook.value.name
        }
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          ebooks.value = data.content.list;
          // 重置分页按钮
          pagination.value.current = params.page;
          pagination.value.total = data.content.total;
        } else {
          message.error(data.message);
        }

      })
    };
    /**
     * 表格点击页面时激活操作
     */
    const handleTableChange = (pagination: any) => {
      console.log("分页参数：" + pagination);
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize
      });
    };
    // 表单
    const categoryIds = ref();
    const ebook = ref();
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const handleModalOk = () => {
      modalLoading.value = true;
      // 解析出表单中的分类一和分类二
      ebook.value.category1Id = categoryIds.value[0];
      ebook.value.category2Id = categoryIds.value[1];
      // 编辑保存电子书
      axios.post("/ebook/save", ebook.value).then((response) => {
        modalLoading.value = true;
        loading.value = false;
        const data = response.data;
        if (data.success) {
          modalVisible.value = false;
          modalLoading.value = false;
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          })
          message.success("操作成功")
        } else {
          modalLoading.value = false;
          message.error(data.message)
        }
      })
    };

    // 编辑电子书方法
    const edit = (record: any) => {
      modalVisible.value = true;
      ebook.value = Tool.copy(record);
      categoryIds.value = [ebook.value.category1Id, ebook.value.category2Id];
    }

    // 新增电子书方法
    const add = () => {
      modalVisible.value = true;
      ebook.value = {};
    }

    // 删除电子书方法
    const handleDelete = (id: number) => {
      axios.delete("/ebook/delete/" + id).then((response) => {
        const data = response.data;
        if (data.success) {
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          })
          message.success("操作成功")
        }
      })
    }
    // 查询出分类信息
    const level1 = ref();
    let categorys: any;
    const handleQueryCategory = () => {
      loading.value = true;
      axios.get("/category/list").then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          level1.value = [];
          categorys = data.content;
          level1.value = Tool.array2Tree(categorys, 0);
          // 让分类查询在表格数据查询之前执行 否则在表格数据渲染时可能会出现分类数据为空情况【异步】
          handleQuery({
            page: 1,
            size: pagination.value.pageSize,
          });
        } else {
          message.error(data.message);
        }
      })
    };

    // 根据id获取分类名
    const getCategoryName = (cid: number) => {
      let res = '';
      categorys.forEach((item: any) => {
        if (cid == item.id) {
          res = item.name;
        }
      });
      return res;
    };


    onMounted(() => {
      handleQueryCategory();
    });
    return {
      ebooks,
      ebook,
      loading,
      columns,
      pagination,
      modalVisible,
      modalLoading,
      handleTableChange,
      edit,
      add,
      handleModalOk,
      handleDelete,
      searchEbook,
      handleQueryByName,
      level1,
      categoryIds,
      getCategoryName
    }
  }
});

</script>
